package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    IRegionService regionService;

    @RequestMapping("list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model){
        return "region/list";
    }

    @RequestMapping("listByParentId")
    @ResponseBody
    public Object listByParentId(Long parentId,String type){
        List<Region> regions = regionService.listByParentId(parentId);
        //如果是tree就返回treeview指定的类型
        if("tree".equals(type)) {
            List<Map> maps = new ArrayList();
            for (Region region : regions) {
                maps.add(region.toTreeViewMap());
            }
            return maps;
        }
        return regions;
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region entity) {
        regionService.saveOrUpdate(entity);
        return new JSONResult(); //象征性返回操作成功
    }

}
